package com.cspg.design.presenter;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

import com.cspg.design.CSPGApplication;
import com.cspg.design.CheckPermissionsActivity;
import com.cspg.design.MainActivity;
import com.cspg.design.R;
import com.cspg.design.bean.UserInfo;
import com.cspg.design.bean.projectBean.ProjectBean;
import com.cspg.design.bean.splash.SplashBean;
import com.cspg.design.bean.userInfoBean.UserInfoBean;
import com.cspg.design.dao.gen.DaoSession;
import com.cspg.design.dao.gen.ProjectBeanDao;
import com.cspg.design.dto.ProjectDto;
import com.cspg.design.model.ProjectModel;
import com.cspg.design.request.Home;
import com.cspg.design.request.Login;
import com.cspg.design.ui.login.LoginActivity;
import com.cspg.design.widget.CSPGProgressBar;
import com.cspg.design.widget.ToastUtils;

import org.greenrobot.greendao.rx.RxDao;
import org.greenrobot.greendao.rx.RxQuery;

import java.util.ArrayList;
import java.util.List;

import q.rorbin.badgeview.Badge;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

public class HomeFragmentPresenter implements IPresenter {
    private final Home homeModel;
    private final Activity activity;

    private CSPGProgressBar cspgProgressBar;
    private RxDao<UserInfoBean, Long> userInfoBeanLongRxDao;

    private Badge badge;

    public HomeFragmentPresenter(Activity activity) {
        this.homeModel = new Home(this);
        this.activity = activity;
    }

    public HomeFragmentPresenter(Activity activity,Badge badge)
    {
        this.homeModel = new Home(this);
        this.activity = activity;
        this.badge = badge;
    }


    public void project()  {
        if(cspgProgressBar == null)
        {
            cspgProgressBar = CSPGProgressBar.show(activity);
        }else {
            cspgProgressBar.show();
        }
        try {
            homeModel.getProject();
        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public void getFailure(String msg) {

        if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
            cspgProgressBar.dismiss();
        }
        ToastUtils.toast(activity, msg);
    }

    public void getTokenExpireFailure() {

        if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
            cspgProgressBar.dismiss();
        }
        Intent intent = new Intent();
        intent.setClass(activity, LoginActivity.class);
        activity.startActivity(intent);
    }

    public void requestSuccess(ProjectModel projectModel) {
        if (projectModel != null) {
            processData(projectModel);
        }
    }

    @Override
    public void netWorkError(String netError) {
//        activity.hideProgress();
//        activity.toast(netError);

        if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
            cspgProgressBar.dismiss();
        }
        ToastUtils.toast(activity, netError);
        if (activity instanceof MainActivity) {
            //activity.openNewActivity(LoginActivity.class);
            Intent intent = new Intent();
            intent.setClass(activity, LoginActivity.class);
            activity.startActivity(intent);
        }
    }

    @Override
    public void httpRequestFailure(String noDataError) {
//        activity.hideProgress();
////        activity.toast(noDataError);
        if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
            cspgProgressBar.dismiss();
        }
        ToastUtils.toast(activity, noDataError);
        if (activity instanceof MainActivity) {
            //activity.openNewActivity(LoginActivity.class);
            Intent intent = new Intent();
            intent.setClass(activity, LoginActivity.class);
            activity.startActivity(intent);
        }
    }

    @Override
    public void httpRequestSuccess() {
//        activity.hideProgress();
        if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
            cspgProgressBar.dismiss();
        }
        if (activity instanceof LoginActivity) {
//            addLocalData();
//            LoginActivity loginActivity = (LoginActivity) activity;
//            loginActivity.openNewActivity(MainActivity.class);
        } else {
//            activity.openNewActivity(MainActivity.class);
//            Intent intent = new Intent();
//            intent.setClass(activity, MainActivity.class);
//            activity.startActivity(intent);
        }
    }
    private void processData(ProjectModel projectModel)
    {
        ListView mListViewRecentTask = activity.findViewById(R.id.lv_recent_task);
        List<ProjectDto> projectDtos = projectModel.getContent();
        List<ProjectBean> projectBeanList = projectModeConverterFactory(projectDtos);
        // get the Rx variant of the note DAO
        DaoSession daoSession = ((CSPGApplication) activity.getApplication()).getDaoSession();
        daoSession.getProjectBeanDao().deleteAll();
        daoSession.getProjectBeanDao().insertOrReplaceInTx(projectBeanList);
        RxQuery<ProjectBean> projectBeanRxQuery = daoSession.getProjectBeanDao()
                .queryBuilder()
                //.where(ProjectBeanDao.Properties.UserName.eq(UserInfo.getInstance().userName))
                .orderAsc(ProjectBeanDao.Properties.Id).rx();
        projectBeanRxQuery.list().observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<List<ProjectBean>>() {
            @Override
            public void call(List<ProjectBean> projectBeans) {
                List<String> projectTitles = new ArrayList<>();
                for (int i = 0; i<projectBeans.size(); i++)
                {
                    ProjectBean projectBean = projectBeans.get(i);
                    if (UserInfo.getInstance().role.contains("设计"))
                    {
                        if (projectBean.getProjectStatus().equals("done"))
                        {
                            projectTitles.add(projectBeans.get(i).getProjectTitle());
                        }
                    }
                    else
                    {

                        if (projectBean.getProjectStatus().equals("doing"))
                        {
                            projectTitles.add(projectBeans.get(i).getProjectTitle());
                        }
                    }
                }
                String[] data = projectTitles.toArray(new String[projectTitles.size()]);
                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(() -> {
                    ArrayAdapter<String> recentTaskAdapter = new ArrayAdapter<String>(activity,android.R.layout.simple_list_item_1, data);
                    mListViewRecentTask.setAdapter(recentTaskAdapter);
                    if (badge!= null)
                    {
                        badge.setBadgeNumber(data.length);
                    }
                });
                if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
                    cspgProgressBar.dismiss();
                }
            }
        });
    }
    private List<ProjectBean> projectModeConverterFactory(List<ProjectDto> projectDtoList)
    {
        List<ProjectBean> projectBeanList = new ArrayList<>();
        for (int i =0 ;i<projectDtoList.size();i++)
        {
            ProjectDto projectDto = projectDtoList.get(i);
            //if (projectDto.getUserName().equals(UserInfo.getInstance().userName))
            //{
                ProjectBean projectBean= new ProjectBean();
                projectBean.setId(projectDto.getId());
                projectBean.setUserName(projectDto.getUserName());
                projectBean.setProjectTitle(projectDto.getProjectTitle());
                projectBean.setProjectId(projectDto.getProjectId());
                projectBean.setProjectStatus(projectDto.getProjectStatus());
                projectBean.setProjectName(projectDto.getProjectName());
                projectBean.setSchemeName(projectDto.getSchemeName());
                projectBean.setSchemaType(projectDto.getSchemaType());
                projectBean.setAffiliattedUnit(projectDto.getAffiliattedUnit());
                projectBean.setProjectCode(projectDto.getProjectCode());
                projectBean.setProjectInvestment(projectDto.getProjectInvestment());
                projectBean.setProjectDate(projectDto.getProjectDate());
                projectBean.setVoltageLevel(projectDto.getVoltageLevel());
                projectBean.setCarDistance(projectDto.getCarDistance());
                projectBean.setHandDistance(projectDto.getHandDistance());
                projectBean.setRemark(projectDto.getRemark());
                projectBeanList.add(projectBean);
            //}
        }
        return projectBeanList;
    }
}
